<template>
  <view class="pages">
    <u-sticky
      class="sticky_c"
      offsetTop="0"
      :style="{ backgroundColor: scrollBgc ? '#E8E2FF' : '' }"
    >
      <h-line :height="statusHeight + 20"></h-line>
      <view class="navbar">
        <view class="nav_b">
          <u-icon name="arrow-left" size="22" color="#333" @click="goBack"></u-icon>
        </view>
        <view class="page_title">产检表</view>
        <view class="nav_right">
          <view class="right_item" @click="navigateTo('/pregnancys/index/time-table/record-test')">
            <image src="@/static/imgs/project_icon.png" mode="scaleToFill" />
            <text>产检记录</text>
          </view>
          <view class="right_item" @click="warnChange">
            <image src="@/static/imgs/warn_icon.png" mode="scaleToFill" />
            <text>提醒</text>
          </view>
        </view>
        <!-- <image @click="toDetail" class="navbar_img" src="@/static/shop/fx.png" mode="widthFix" /> -->
      </view>
      <h-line height="13"></h-line>
      <view class="nickname">
        <view style="display: flex">
          <image
            :src="
              AntenatalUserinfo.avatar ||
              'https://ossresource.miyingbl.com/uploads/20231230/h-bl-app/1703899956674'
            "
            mode="scaleToFill"
          />
          <view class="user_info">
            <text>{{ AntenatalUserinfo.name }}</text>
            <view class="star-box">
              <view class="star">
                <view style="font-size: 22rpx; color: #7d7d7d; display: flex; align-items: center">
                  <view v-if="AntenatalUserinfo.type == 1" style="margin-right: 10rpx">{{
                    AntenatalUserinfo.tag || ''
                  }}</view>
                  <view v-if="AntenatalUserinfo.type == 1">(预产期</view>
                  <view v-else>(生产期</view>
                  <view v-if="AntenatalUserinfo.type == 1" style="margin-top: 2rpx">{{
                    AntenatalUserinfo.due_date || ''
                  }}</view>
                  <view v-else style="margin-top: 2rpx">{{
                    AntenatalUserinfo.product_date || ''
                  }}</view>
                  <view>)</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view
          class="add_production"
          @click="navigateTo('/pregnancys/index/time-table/add-product-test')"
          >添加产检</view
        >
      </view>
      <view class="round_edge"></view>
    </u-sticky>
    <view class="antenatal_box" v-for="(item, index) in prenatalList" :key="index">
      <view class="antenatal_title">
        <view>
          <text class="antenatal_num">{{ item.name }}</text>
          <view class="antenatal_main">
            <view>必查项目：</view>
            <view v-if="item.type == 0" class="antenatal_main_item">
              <text v-for="(i, n) in item.bcxm_cate" :key="n">{{ i }}</text>
            </view>
            <view class="add_antenatal_item_x" v-if="item.type == 1">
              <text class="text_x" v-for="(i, n) in item.user_cate" :key="n">{{ i.name }}</text>
            </view>
            <image
              class="add_antenatal_img"
              @click="
                navigateTo(`/pregnancys/index/time-table/add-product-test?id=${item.id}&isBianji=1`)
              "
              v-if="item.type == 1"
              src="@/static/baby/bianji.png"
              mode="scaleToFill"
            />
          </view>
        </view>
        <u-icon
          @click="
            navigateTo(`/pregnancys/index/time-table/record-detail?id=${item.id}&type=${item.type}`)
          "
          name="arrow-right"
          size="19"
          color="#333"
        ></u-icon>
      </view>
      <view class="time_select" @click="toCheckReport(item.id)">
        <text style="margin-top: 2rpx">{{ item.check_date }}</text>
        <text class="weeks">{{ item.week_day }}</text>
        <u-icon name="arrow-down" size="10" color="#999999"></u-icon>
      </view>
      <view v-if="item.status == 1" class="completed">已完成</view>
      <view v-if="item.status == 2" class="completed expired">已过期</view>
      <view v-if="item.is_next == 1" class="completed next">下一次</view>
      <view v-if="item.type == 1" class="completed add_new">新增</view>
    </view>
    <!-- 弹出 -->
    <u-popup
      :show="warnShow"
      :safeAreaInsetBottom="false"
      mode="center"
      @touchmove.stop.prevent="moveHandle"
      @close="warnClose"
      :round="10"
    >
      <view class="warn_box">
        <view class="warn_title">您已设置产检提醒</view>
        <view class="warn_main">app将在产检前一天10:00am </view>
        <view class="warn_main">向您推送提醒</view>
        <view>
          <u-button
            type="primary"
            @click="saveEualuation"
            shape="circle"
            text="我知道了"
            class="custom_style"
          ></u-button>
        </view>
      </view>
    </u-popup>
    <!-- 时间选择 -->
    <u-datetime-picker
      :formatter="formatter"
      title="请选取实际产检日期"
      :show="showDatePicker"
      v-model="newDate"
      mode="datetime"
      :maxDate="1786778555000"
      @close="showDatePicker = false"
      @cancel="showDatePicker = false"
      :closeOnClickOverlay="true"
      @confirm="onDateConfirm"
    ></u-datetime-picker>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { useMemberStore, useSystemStore } from '@/stores'
import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app'
import { navigateBack, navigateTo, formatDate, showToast } from '@/utils'
import {
  getPrenatalExamination,
  getAntenatalUserinfo,
  getOpenPush,
  editCheckDate,
} from '@/api/pregnancy/index'
const userStore = useMemberStore()
const scrollBgc = ref(false)
const defaultDate = ref('')
const statusHeight = ref()
const warnShow = ref(false)
const showDatePicker = ref(false)
const newDate = ref(Date.now())
const maxDate = ref(Date.now())
//提醒开关
const isOpenPush = ref(false)
//个人信息
const AntenatalUserinfo = ref({})
//列表
const prenatalList = ref([])
//新增列表
const addprenatalList = ref([])
//展示时间
const revealVal = ref('')
//周几
const weeks = ref(['周日', '周一', '周二', '周三', '周四', '周五', '周六'])
const weeksValue = ref('')
const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  return value
}
//设置时间参数
const datePreams = ref({
  id: 0,
  date: '',
})
onShow(() => {
  uni.getSystemInfo({
    success: (e) => {
      statusHeight.value = e?.statusBarHeight * 2
    },
  })

  getPrenatalList()
  getAntenatalUserinfoData()
})
//产检主页个人信息
async function getAntenatalUserinfoData() {
  const res = await getAntenatalUserinfo()
  if (res.code == 200) {
    AntenatalUserinfo.value = res.data.data[0]
    userStore.recordAvatar = res.data.data[0].avatar
  }
}
//获取列表
async function getPrenatalList() {
  const res = await getPrenatalExamination()
  if (res.code == 200) {
    prenatalList.value = res.data.data
  }
}
// 返回
function goBack() {
  navigateBack()
}
//提醒
async function warnChange() {
  const res = await getOpenPush({ openStatus: 1 })
  if (res.code == 200) {
    getQuanxian()
  } else {
    showToast(res.msg)
  }
}
//消息通知权限
function getQuanxian() {
  let platform = uni.getSystemInfoSync().platform //首先判断app是安卓还是ios
  console.log(platform)
  if (platform == 'ios') {
    var UIApplication = plus.ios.import('UIApplication')
    var app = UIApplication.sharedApplication()
    var enabledTypes = 0
    if (app.currentUserNotificationSettings) {
      var settings = app.currentUserNotificationSettings()
      enabledTypes = settings.plusGetAttribute('types')
      console.log('enabledTypes1:' + enabledTypes)
      if (enabledTypes == 0) {
        //如果enabledTypes = 0 就是通知权限没有开启
        uni.showModal({
          title: '提示',
          content: '是否前往打开通知权限',
          success: (res) => {
            if (res.confirm) {
              openTongZhi()
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      } else {
        warnShow.value = true
      }
    }
    plus.ios.deleteObject(settings)
  } else if (platform == 'android') {
    var main = plus.android.runtimeMainActivity()
    var pkName = main.getPackageName()
    var uid = main.getApplicationInfo().plusGetAttribute('uid')
    var NotificationManagerCompat = plus.android.importClass(
      'android.support.v4.app.NotificationManagerCompat',
    )
    if (NotificationManagerCompat == null) {
      NotificationManagerCompat = plus.android.importClass(
        'androidx.core.app.NotificationManagerCompat',
      )
    }
    var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled()
    console.log(areNotificationsEnabled)
    if (areNotificationsEnabled) {
      warnShow.value = true
    } else {
      uni.showModal({
        title: '提示',
        content: '是否前往打开通知权限',
        success: (res) => {
          if (res.confirm) {
            openTongZhi()
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        },
      })
    }
  }
}
//前往打开消息通知
function openTongZhi() {
  let platform = uni.getSystemInfoSync().platform //获取安卓还是ios
  if (platform == 'ios') {
    //如果机型是ios，ios由于权限问题，可能需要手动开启
    var UIApplication = plus.ios.import('UIApplication')
    var app = UIApplication.sharedApplication()
    var settings = app.currentUserNotificationSettings()
    enabledTypes = settings.plusGetAttribute('types')
    var NSURL2 = plus.ios.import('NSURL')
    var setting2 = NSURL2.URLWithString('app-settings:')
    var application2 = UIApplication.sharedApplication()
    application2.openURL(setting2)
    plus.ios.deleteObject(setting2)
    plus.ios.deleteObject(NSURL2)
    plus.ios.deleteObject(application2)
    plus.ios.deleteObject(settings)
  } else if (platform == 'android') {
    var main = plus.android.runtimeMainActivity()
    var pkName = main.getPackageName()
    var uid = main.getApplicationInfo().plusGetAttribute('uid')
    var Intent = plus.android.importClass('android.content.Intent')
    var Build = plus.android.importClass('android.os.Build')
    if (Build.VERSION.SDK_INT >= 26) {
      var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS')
      intent.putExtra('android.provider.extra.APP_PACKAGE', pkName)
    } else if (Build.VERSION.SDK_INT >= 21) {
      var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS')
      intent.putExtra('app_package', pkName)
      intent.putExtra('app_uid', uid)
    } else {
      intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
      var uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
      intent.setData(uri)
    }
    main.startActivity(intent)
  }
}
function warnClose() {
  warnShow.value = false
}
function saveEualuation() {
  warnShow.value = false
}
//时间选择
function onDateConfirm(e) {
  console.log(e)
  showDatePicker.value = false
  newDate.value = e.value
  revealVal.value = formatDate(e.value, 'YYYY-MM-DD')
  let week = new Date(revealVal.value).getDay()
  weeksValue.value = weeks.value[week]
  datePreams.value.date = `${revealVal.value} ${weeksValue.value}`
  editCheckDate(datePreams.value).then((res) => {
    if (res.code == 200) {
      showToast(res.msg)
      getPrenatalList()
    }
  })
}

function toCheckReport(id) {
  showDatePicker.value = true
  datePreams.value.id = id
}
function moveHandle() {
  return false
}
//转周
function getWeekday(dateString) {
  var dateObj = new Date(dateString)
  var weekday = dateObj.getDay()
  var weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return weekdays[weekday]
}
</script>

<style lang="scss" scoped>
.sticky_c {
  top: 0 !important;
  background: url('@/static/imgs/time_table_bg.png') no-repeat;
  background-size: 100%;
  .navbar {
    padding: 0 24rpx;
    width: 100vw;
    height: 100rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    box-sizing: border-box;
    .page_title {
      font-family: PingFang SC, PingFang SC;
      font-weight: 600;
      font-size: 36rpx;
      color: #333333;
      margin-left: 11rpx;
      margin-right: 20rpx;
      line-height: 100rpx;
      text-align: center;
      flex: 1;
    }
    .nav_b {
      width: 160rpx;
      height: 32rpx;
      padding: 30rpx 0;
    }
    .navbar_img {
      width: 32rpx;
      height: 32rpx;
      padding: 34rpx 0;
    }
    .nav_right {
      display: flex;
      align-items: center;
      .right_item {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-left: 20rpx;
        image {
          width: 30rpx;
          height: 30rpx;
          margin-bottom: 4rpx;
        }
        text {
          font-size: 16rpx;
          color: #000000;
        }
      }
    }
  }
  .nickname {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 680rpx;
    margin: 0 auto;
    margin-bottom: 40rpx;
    image {
      width: 98rpx;
      height: 98rpx;
      border-radius: 50%;
    }
    .user_info {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      align-items: flex-start;
      margin-left: 14rpx;
      text {
        font-size: 32rpx;
        color: #000000;
      }
    }
    .add_production {
      width: 160rpx;
      height: 54rpx;
      background: #a28aff;
      border-radius: 56rpx 56rpx 56rpx 56rpx;
      font-size: 24rpx;
      color: #ffffff;
      text-align: center;
      line-height: 54rpx;
    }
  }
  .round_edge {
    width: 750rpx;
    height: 40rpx;
    background: #f6f6f6;
    border-radius: 25rpx 25rpx 0rpx 0rpx;
  }
}
.pages {
  width: 750rpx;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f6f6f6;
  font-family: PingFang-SC-Bold, PingFang-SC;
  padding-bottom: 30rpx;
  .antenatal_box {
    width: 702rpx;
    padding-bottom: 30rpx;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    margin-bottom: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    .antenatal_title {
      width: 645rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1rpx solid #f6f6f6;
      margin-top: 30rpx;
      .antenatal_num {
        font-weight: 600;
        font-size: 32rpx;
        color: #333333;
      }
      .antenatal_main {
        display: flex;
        font-size: 26rpx;
        color: #333333;
        margin: 20rpx 0;
        .antenatal_main_item {
          width: 400rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          text {
            margin-right: 10rpx;
          }
        }
        .add_antenatal_item_x {
          max-width: 15ch;
          height: 36rpx;
          overflow: hidden;
          .text_x {
            margin-right: 10rpx;
          }
        }
        .add_antenatal_img {
          width: 27rpx;
          height: 27rpx;
          margin-left: 10rpx;
          margin-top: 3rpx;
        }
      }
    }
    .time_select {
      width: 645rpx;
      display: flex;
      align-items: center;
      font-size: 22rpx;
      color: #848484;
      margin-top: 18rpx;
      .weeks {
        margin: 0 10rpx 0 20rpx;
      }
    }
    .completed {
      width: 101rpx;
      height: 39rpx;
      background: #37bd6f;
      border-radius: 0rpx 16rpx 0rpx 16rpx;
      font-size: 22rpx;
      color: #ffffff;
      text-align: center;
      line-height: 39rpx;
      position: absolute;
      top: 0;
      right: 0;
    }
    .expired {
      background: #808080;
    }
    .next {
      background: #a28aff;
    }
    .add_new {
      background: #ff8d9d;
    }
  }
}
//弹框
.warn_box {
  width: 465rpx;
  background: #ffffff;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  .warn_title {
    font-weight: 600;
    font-size: 30rpx;
    color: #333333;
    margin-bottom: 20rpx;
  }
  .warn_main {
    width: 400rpx;
    font-size: 24rpx;
    color: #333333;
    text-align: center;
    margin-bottom: 4rpx;
  }
  .custom_style {
    width: 178rpx;
    height: 49rpx;
    background: #a28aff;
    border-radius: 58rpx 58rpx 58rpx 58rpx;
    margin-top: 30rpx;
  }
}
</style>
